package io.noties.markwon.app.samples;


import com.noties.markwon.utils.LogUtils;
import com.noties.markwon.wrapper.text.SpannableStringBuilder;

import io.noties.markwon.Markwon;
import io.noties.markwon.app.sample.Tags;
import io.noties.markwon.app.sample.ui.MarkwonTextViewSample;
import io.noties.markwon.sample.annotations.MarkwonArtifact;
import io.noties.markwon.sample.annotations.MarkwonSampleInfo;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author: yangrui
 * @function: ExcludeFromParsingSample
 * @date: 2021/3/23
 */

@MarkwonSampleInfo(
  id = "20201111221945",
  title = "Exclude part of input from parsing",
  description = "Exclude part of input from parsing by splitting input with delimiters",
  artifacts = MarkwonArtifact.CORE,
  tags = Tags.parsing
)
class ExcludeFromParsingSample extends MarkwonTextViewSample {

  final static String EXCLUDE_START = "##IGNORE##";
  final static String EXCLUDE_END = "--IGNORE--";
  private final static String RE = "EXCLUDE_START([\\s\\S]*?)EXCLUDE_END";

  @Override
  public void render() {

    // cannot have continuous markdown between parts (so a node started in one part and ended in other)
    //  with this approach
    // also exclude will start a new block and won't seamlessly continue any existing markdown one (so
    //  if started inside a blockquote, then blockquote would be closed)

    final String md = "" +
      "# Hello\n" +
      "we are **going** to exclude some parts of this input _from_ parsing\n" +
      "$EXCLUDE_START\n" +
      "what is **good** is that we\n" +
      "> do not need to care about blocks or inlines\n" +
      "* and\n" +
      "* everything\n" +
      "* else\n" +
      "$EXCLUDE_END\n" +
      "**then** markdown _again_\n" +
      "and empty exclude at end: $EXCLUDE_START$EXCLUDE_END";

    final Markwon markwon = Markwon.create(context);
    final Matcher matcher = Pattern.compile(RE, Pattern.MULTILINE).matcher(md);

    SpannableStringBuilder builder = new SpannableStringBuilder();

    int end = 0;

    while (matcher.find()) {
      final int start = matcher.start();
      LogUtils.i(this.getClass().getSimpleName(),String.format("%d%d%s",end,start,md.substring(end,start)));
      builder.append(markwon.toMarkdown(md.substring(end, start)));
      builder.append(matcher.group(1));
      end = matcher.end();
    }

    if (end != md.length()) {
      builder.append(markwon.toMarkdown(md.substring(end)));
    }

    markwon.setParsedMarkdown(textView, builder);
  }
}